package com.syerit.modules.worldgreen3d.control.commands
{
	import br.com.stimuli.loading.BulkErrorEvent;
	import br.com.stimuli.loading.BulkLoader;
	
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.arc90.modular.ModuleSequenceCommand;
	import com.syerit.modules.worldgreen3d.control.events.LoadDataEvent;
	import com.syerit.modules.worldgreen3d.control.events.LoadModuleDataEvent;
	import com.syerit.modules.worldgreen3d.model.ModuleModelLocator;
	
	import flash.events.Event;
	
	/**
	 * @version $Revision: $
	 */
	public class LoadModuleDataCommand extends ModuleSequenceCommand
	{  
		private var appModel :ModuleModelLocator = ModuleModelLocator.getInstance();
		private var $loader:BulkLoader;
		
	 	public function LoadModuleDataCommand()
	 	{
	 		trace("com.modules.worldgreen3d.control.commands.LoadModuleDataCommand: Waiting for AppData...");
	 		//appModel.log.debug("com.control.commands.LoadAppDataCommand: Waiting for AppData...");
		}    
	  	override public function execute( _event : CairngormEvent ) : void
   		{
   			//Set up appModel
   			var e:LoadModuleDataEvent = _event as LoadModuleDataEvent;
   			appModel.viewModel.module = e.module;
			
			//Loading AppData

			$loader = new BulkLoader("initModuleLoader");
			$loader.add(appModel.settingsModel.prefix+"data/appData.xml",{id:"xmlData",type:"xml"});
			$loader.addEventListener(BulkLoader.COMPLETE,onDataLoaded);
			$loader.addEventListener(BulkLoader.ERROR,loadError);
			$loader.start();
   		}
   		private function onDataLoaded(_e:Event):void
   		{
   			_e.target.removeEventListener(BulkLoader.COMPLETE,onDataLoaded);
   			appModel.loadedDataModel.appData = _e.target.getXML("xmlData",true);
   			BulkLoader._allLoaders["initModuleLoader"]=null;
   			var event:LoadDataEvent = new LoadDataEvent();
   			trace("com.modules.worldgreen3d.control.commands.LoadModuleDataCommand: XML AppData Loaded Successfully: \n",appModel.loadedDataModel.appData);
   			//appModel.log.debug("com.modules.worldgreen3d.control.commands.LoadModuleDataCommand: XML AppData Loaded Successfully: \n",appModel.loadedDataModel.appData);
   			event.dispatch();
   		}
   		private function loadError(_e:BulkErrorEvent):void
		{
        	/*for each (var loadingItem:* in _e.errors){
         		trace("#ERROR(_b.objects.BasePage):",loadingItem, "has failed to load");
         		
        	}*/
        	trace("#ERROR(com.modules.worldgreen3d.control.commands.LoadModuleDataCommand):",_e.errors, "has failed to load");
		}
	}
}